package com.mj.mafeed.service;

import org.codehaus.jackson.map.ObjectMapper;

import android.content.Context;

import com.mj.mafeed.bean.ProductCategoryJSON;
import com.mj.mafeed.bean.ProductCategoryListJSON;
import com.mj.mafeed.config.Constants;
import com.mj.mafeed.dao.ProductCategoryDao;
import com.mj.mafeed.util.HttpUtils;

/**
 * 商品分类
 * @author zhaominglei
 * @date 2016-1-9
 * 
 */
public class ProductCategoryService extends BaseService {
	private ProductCategoryDao productCategoryDao = new ProductCategoryDao();
	
	/**
	 * 所有商品分类
	 */
	public ProductCategoryListJSON getAll() {
		StringBuilder url = new StringBuilder(Constants.PRODUCTCATEGORY_ALL_URL);
		String result = HttpUtils.doGet(url.toString());
		if (result != null && !result.equals("")) {
			try {
				ProductCategoryListJSON productCategoryListJSON = new ObjectMapper().readValue(result, ProductCategoryListJSON.class);
				return (productCategoryListJSON != null) ? productCategoryListJSON : null; 
			} catch (Exception e) {
				e.printStackTrace();
			}
		}		
		return null;
	}
	
	/**
	 * 所有商品分类
	 */
	public ProductCategoryListJSON getAll(Context context) {
		return productCategoryDao.getAll(context);
	}
	
	/**
	 * 同步商品分类
	 */
	public void syncProductCategory(Context context) {
		ProductCategoryListJSON productCategoryListJSON = getAll();
		if (productCategoryListJSON != null 
				&& productCategoryListJSON.getRecordList() != null 
				&& !productCategoryListJSON.getRecordList().isEmpty()) {
			productCategoryDao.deleteAll(context);
			for(ProductCategoryJSON productCategoryJSON:productCategoryListJSON.getRecordList()) {
				productCategoryDao.save(context, productCategoryJSON);
			}
		}
	}
}
